package m.common.model.util;

import m.system.exception.MException;
import m.system.util.StringUtil;

import java.util.*;

public class FromQuerySql implements IModelQuery {
    private final StringBuilder sqlFrom;
    private final List<String> fieldNames;//查询的属性
    private final List<Object> paramList;

    public FromQuerySql(){
        this.sqlFrom=new StringBuilder();
        this.fieldNames=new ArrayList<>();
        this.paramList=new ArrayList<>();
    }

    /**
     * 追加sql语句和参数
     */
    public FromQuerySql append(String sql,Object... params){
        sqlFrom.append(sql).append(" ");
        paramList.addAll(Arrays.asList(params));
        return this;
    }

    @Override
    public FromQuerySql addField(String... fieldName) {
        for(String f : fieldName) {
            if(!StringUtil.isSpace(f)&&!this.fieldNames.contains(f)) {
                this.fieldNames.add(f);
            }
        }
        return this;
    }

    @Override
    public String getAlias4Field(String field) {
        if(this.fieldNames.contains(field)){
            return field;
        }
        return null;
    }

    @Override
    public QueryParameter getQueryParameter() throws MException {
        return new QueryParameter(sqlFrom.toString(),paramList);
    }
}
